package com.hundsun.aitest.controller;

import com.hundsun.aitest.common.Result;
import com.hundsun.aitest.util.TaskProgress;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.concurrent.ConcurrentHashMap;

@Controller
@Slf4j
public class TaskStatusController {

    // 任务进度存储
    private final ConcurrentHashMap<String, TaskProgress> taskProgressMap;

    @Autowired
    public TaskStatusController(ConcurrentHashMap<String, TaskProgress> taskProgressMap) {
        this.taskProgressMap = taskProgressMap;
    }

    @GetMapping("/taskStatus")
    @ResponseBody
    public Result<String> getTaskStatus(@RequestParam String taskId) {
        Result<String> result = new Result<>();
        try {
            TaskProgress progress = taskProgressMap.get(taskId);
            if (progress != null) {
                result.setSuccess(true);
                int percent = (int) ((double) progress.getCompleted() / progress.getTotal() * 100);
                result.setData(String.valueOf(percent));
            } else {
                result.setSuccess(false);
                result.setData("任务ID未找到");
            }
        } catch (Exception e) {
            log.error("查询任务状态时发生错误，任务ID：{}", taskId, e);
            result.setSuccess(false);
            result.setData("任务状态查询失败");
        }
        return result;
    }
}